package com.yqfk.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yqfk.auto.JSONAuthentication;
import com.yqfk.entity.YUser;
import com.yqfk.mapper.YClassMapper;
import com.yqfk.mapper.YUserMapper;
import com.yqfk.response.Result;
import com.yqfk.utils.UpPhotoNameUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.security.util.Password;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yqfk
 * @since 2022-03-30
 */
@RestController
@RequestMapping("/y-user")
public class YUserController extends JSONAuthentication {
    @Autowired
    YUserMapper yUserMapper;
    @Autowired
    YClassMapper yClassMapper;
    @ApiOperation(value = "添加用户")
    @PostMapping("/add")
    public void addCar(@RequestParam("file") MultipartFile file,  HttpServletRequest request, HttpServletResponse response, @RequestParam("username") String username, @RequestParam("password") String password) throws Exception {
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("username",username);
        YUser baMeans1=yUserMapper.selectOne(wrapper);
        if(baMeans1!=null){
            Result error = Result.error().message("该用户名已被占用");
            this.WriteJSON(request, response, error);
        }else{
            YUser yUser=new YUser();
            yUser.setUsername(username);
            String password1 = new BCryptPasswordEncoder().encode(password);
            yUser.setPassword(password1);
            byte[] bytes = file.getBytes();
            String imageFileName = file.getOriginalFilename();
            String fileName = UpPhotoNameUtils.getPhotoName("img",imageFileName);
            Path path = Paths.get("D:\\疫情防控\\epi\\src\\assets\\picture\\" + fileName);
            //“C:\\框架\\D4\\d4_pc_ui\\src\\assets\\images\\img\\”为本地目录
            Files.write(path, bytes);//写入文件
            String avatar_url=fileName;
            yUser.setPicture(avatar_url);
            response.reset();
            if(yUserMapper.insert(yUser)>0){
                Result ok = Result.ok();
                this.WriteJSON(request, response, ok);
            }else{
                Result error = Result.error();
                this.WriteJSON(request, response, error);
            }
        }
    }
    @ApiOperation(value = "删除用户")
    @PostMapping("/del")
    public void delUser(HttpServletRequest request, HttpServletResponse response, @RequestParam("userId") int userId) throws Exception {
        int i = yUserMapper.deleteById(userId);
        if (i > 0) {
            Result ok = Result.ok();
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "修改密码")
    @PostMapping("/updPassword")
    public void updUser(HttpServletRequest request, HttpServletResponse response, @RequestParam("password") String password, @RequestParam("rpassword") String rpassword, @RequestParam("id") int id) throws Exception {
        YUser shUser = yUserMapper.selectById(id);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (encoder.matches(password, shUser.getPassword())) {
            String newPassword = new BCryptPasswordEncoder().encode(rpassword);
            shUser.setPassword(newPassword);
            if (yUserMapper.updateById(shUser) > 0) {
                Result ok = Result.ok();
                this.WriteJSON(request, response, ok);
            } else {
                Result error = Result.error();
                this.WriteJSON(request, response, error);
            }
        } else {
            Result error = Result.error();
            error.setMessage("密码不正确");
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "通过用户名查找用户")
    @PostMapping("/findByName")
    public void findById(HttpServletRequest request, HttpServletResponse response, @RequestParam("username") String username, @RequestParam("size") int size, @RequestParam("current") int current) throws Exception {

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.like("username", username);
        Page<YUser> shUserPage = new Page<>(current, size);
        Page<YUser> shUserPages = yUserMapper.selectPage(shUserPage, wrapper);
        List<YUser> records = shUserPages.getRecords();

        for (YUser a: records){
            QueryWrapper wrapper1=new QueryWrapper();
            wrapper1.eq("user_id",a.getId());
            if(yClassMapper.selectOne(wrapper1)!=null){
            a.setYClass(yClassMapper.selectOne(wrapper1));
            }
        }
        int total = yUserMapper.selectCount(wrapper);
        if (records.size() > 0) {
            Result ok = Result.ok().data("userList", records).data("total", total);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "查找所有用户")
    @PostMapping("/findAllUser")
    public void findById(HttpServletRequest request, HttpServletResponse response, @RequestParam("size") int size, @RequestParam("current") int current) throws Exception {
        Page<YUser> shUserPage = new Page<>(current, size);
        Page<YUser> shUserPages = yUserMapper.selectPage(shUserPage, null);
        List<YUser> records = shUserPages.getRecords();
        for (YUser a: records){
            QueryWrapper wrapper1=new QueryWrapper();
            wrapper1.eq("user_id",a.getId());
            if(yClassMapper.selectOne(wrapper1)!=null){
                a.setYClass(yClassMapper.selectOne(wrapper1));
            }
        }
        int total = yUserMapper.selectCount(null);
        if (records.size() > 0) {
            Result ok = Result.ok().data("userList", records).data("total", total);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "通过id查找用户")
    @PostMapping("/findByUserId")
    public void findByUserId(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") int id) throws Exception {
        YUser shUser = yUserMapper.selectById(id);
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("user_id", shUser.getId());

        QueryWrapper wrapper1=new QueryWrapper();
        wrapper1.eq("user_id",shUser.getId());
        if(yClassMapper.selectOne(wrapper1)!=null){
            shUser.setYClass(yClassMapper.selectOne(wrapper1));
        }

        if (shUser != null) {
            Result ok = Result.ok().data("user", shUser);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "通过id查找用户添加资料")
    @PostMapping("/findByUserIdADDMeans")
    public void findByUserIdADDMeans(HttpServletRequest request, HttpServletResponse response, @RequestBody YUser yUser) throws Exception {
        if(yUser.getPhone()!=null){
            yUser.setPhone(yUser.getPhone());
        }
        if(yUser.getName()!=null){
            yUser.setName(yUser.getName());
        }
        if(yUser.getAddress()!=null){
            yUser.setAddress(yUser.getAddress());
        }
        if(yUser.getSfz()!=null){
            yUser.setSfz(yUser.getSfz());
        }
        if (yUserMapper.updateById(yUser)>0) {
            Result ok = Result.ok();
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
}

